package com.hhq.cloud.config;

import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientBuilder;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Configuration
public class KubernetesConfig {

    @Bean
    public KubernetesClient kubernetesClient() {
        // 默认 kubeconfig 路径（也可指定绝对路径）
        String kubeConfigPath = System.getProperty("user.home") + "/.kube/config";
        File file = new File(kubeConfigPath);
        Config config = Config.fromKubeconfig(file);
        return new KubernetesClientBuilder().withConfig(config).build();
    }


    /**
     * 获取k8s线程池
     * @return
     */
    @Bean
    public ThreadPoolExecutor KubernetesThreadPoolExecutor(){
        int corePoolSize = Runtime.getRuntime().availableProcessors();
        // 为线程设置一个自定义的名称
        return new ThreadPoolExecutor(corePoolSize, corePoolSize * 2, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1000), new ThreadFactory() {
            private int threadCount = 0;

            @Override
            public Thread newThread(Runnable r) {
                threadCount++;
                // 为线程设置一个自定义的名称
                Thread thread = new Thread(r);
                thread.setName("Kubernetes-Thread-" + threadCount);
                return thread;
            }
        });
    }


}
